<!DOCTYPE html>
<html lang="zh" xmlns:th="http://www.thymeleaf.org" xmlns:shiro="http://www.pollix.at/thymeleaf/shiro">
<head>
	<th:block th:include="include :: header('选品库')" />
	<th:block th:include="include :: businessCSS" />
	<style>

		.preservationBtn{padding: 10px;text-align: center;}
		.preservationBtn input{font-size: 16px;background-color: rgb(80, 138, 238);color: #fff;border: none;padding: 5px 30px;border-radius: 10px;cursor: pointer;}
		/* .layui-border-box{height: 350px !important;} */
		/* .layui-table-body{height: 240px !important;} */
		.layui-table-tool-temp{padding-right: 30px;}
        .getDetailUpload,.getDetailUpload2{cursor: pointer;}

	</style>
</head>
<body class="no-skin">
<div class="main-container" id="main-container">
	<div class="main-content">
	<form class="layui-form head-form">
	    <div class="north" style="background-color: #fff;margin-bottom: 10px;">
			<div class="forminput"></div>
			<div class="layui-form-item preservationBtn" >
				<input th:if="${extraButton.lplbtn}" type="button" lay-submit lay-filter="btn-batch-upload-img" id="btn-batch-upload-img" value="批量导入图片">
				<input th:if="${enableEdit} == 1 and ${extraButton.xgbtn}" type="button" lay-submit lay-filter="btn-edit" id="btn-edit" value="修改">
                <input th:if="${extraButton.dcbtn}" type="button" lay-submit lay-filter="btn-export" id="btn-export" value="导出">
			</div>

    	</div>

    </form>
	</div>
</div>

<div>
    <table class="layui-hide" id="zjdhtable" lay-filter="zjtable"></table>
    <script type="text/html" id="barDh">
        <button class="layui-btn layui-btn-danger layui-btn-xs dhicon dh-remove" lay-event="del" th:if="${extraButton.sczjbtn}">&nbsp;删除</button>
    </script>
    <script type="text/html" id="zjtoolbar">
        <div style="padding: 16px;display: flex;justify-content: space-between;">
            <div  style="font-weight: 700;font-size: 18px;">子件列表</div>
    		<div style="display: flex;" th:if="${enableEdit} == 1">
                <div style="margin-left:10px" class="layui-btn layui-btn-normal layui-table-tools" lay-event="phbtn" shiro:hasPermission="business:productlisting:view" th:if="${extraButton.phbtn}">
    				<p class="dhicon" style="color:white;font-size:14px;">铺货</p>
    			</div>
    			<div style="margin-left:10px" class="layui-btn layui-btn-normal layui-table-tools" lay-event="addbtn" shiro:hasPermission="business:productlisting:add" th:if="${extraButton.xzzjbtn}">
    				<p class="dhicon dh-plus" style="color:white;font-size:14px;"><span class="fa_span">新增明细</span></p>
    			</div>
    			<div>
    				<input style="margin-left:10px" class="layui-btn layui-table-tools" type="button" lay-submit="" lay-filter="zjbtn_save" value="保存" th:if="${extraButton.bcbtn}">
    			</div>
    		</div>
    	</div>
    </script>
</div>

<!-- <div>
    <table class="layui-hide" id="jpdhtable" lay-filter="jptable"></table>
    <script type="text/html" id="barDh">
        <a class="layui-btn layui-btn-danger layui-btn-xs dhicon dh-remove" th:disabled="${enableEdit} == 1 ?false:true" lay-event="del">&nbsp;删除</a>
    </script>
    <script type="text/html" id="jptoolbar">
        <div style="padding: 16px;display: flex;justify-content: space-between;">
            <div  style="font-weight: 700;font-size: 18px;">竞品列表</div>
    		<div style="display: flex;" th:if="${enableEdit} == 1">
					<div class="layui-btn layui-btn-normal layui-table-tools" lay-event="addbtn" shiro:hasPermission="business:productlisting:add">
    				<p class="dhicon dh-plus" style="color:white;font-size:14px"><span class="fa_span">新增明细</span></p>
    			</div>
    			<div>
    				<input style="margin-left:10px" class="layui-btn layui-table-tools" type="button" lay-submit="" lay-filter="btn_save" value="保存">
    			</div>
    		</div>
    	</div>
    </script>
</div> -->
<th:block th:include="include :: footer" />
<th:block th:include="include :: businessJS" />

<!-- 明细特殊模板自生成 -->
<div th:each="dfpl:${gridColumnsZJ.dictionaryForPageFieldList}" th:if="${dfpl.fieldFrontType ne 't_text'}" th:remove="tag">
    <script type="text/html" th:if="${dfpl.fieldFrontType eq 't_decimal' and #strings.containsIgnoreCase(dfpl.fieldFrontTemplet,'p_')}" th:id="'decimal_'+${dfpl.fields}">
        <span>{{d.[[${dfpl.fields}]] + '%'}}</span>
    </script>
    <script type="text/html" th:if="${(dfpl.fieldFrontType eq 't_date' or dfpl.fieldFrontType eq 't_datetime')}" th:id="'date_'+${dfpl.fields}">
        <input type="text" th:value="'{{d.'+${dfpl.fields}+'?d.'+${dfpl.fields}+':``}}'" th:fft="${dfpl.fieldFrontType}" class="layui-input layui-table-date" style="position:absolute;overflow:hidden;z-index:2;left:0;margin:0;height:32px;padding-right:30px" autocomplete="off">
        <i class="dhicon dh-calendar icon_date_business" style="z-index:3;font-size:0"></i>
    </script>
    <script type="text/html" th:if="${dfpl.fieldFrontType eq 't_buttontext'}" th:id="'buttontext_'+${dfpl.fields}">
        <span th:text="'{{d.'+${dfpl.fields}+'}}'"></span>
        <i class="layui-icon layui-icon-more" th:onclick="getMore([[${dfpl.fields}]],{{d.LAY_TABLE_INDEX}},[[${dfpl.fieldName}]],[[${dfpl.fieldSearchType}]])" style="position:absolute;right:8px;z-index:3"></i>
    </script>
    <script type="text/html" th:if="${dfpl.fieldFrontType eq 't_buttontextedit'}" th:id="'buttontextedit_'+${dfpl.fields}">
        <input type="text" th:value="'{{d.'+${dfpl.fields}+'}}'" class="layui-input" style="position:absolute;overflow:hidden;z-index:2;left:0;margin:0;height:32px;padding-right:30px" th:onkeyup="inputOnTable(this,[[${dfpl.fields}]])" autocomplete="off">
        <i class="layui-icon layui-icon-more" th:onclick="getMore([[${dfpl.fields}]],{{d.LAY_TABLE_INDEX}},[[${dfpl.fieldName}]],[[${dfpl.fieldSearchType}]])" style="position:absolute;right:8px;z-index:3"></i>
    </script>
    <script type="text/html" th:if="${dfpl.fieldFrontType eq 't_textarea' or (dfpl.fieldFrontType eq 't_textarea' and gridColumnsZJ.readOnly)}" th:id="'textarea_'+${dfpl.fields}">
        <span th:utext="'{{typeof d.'+${dfpl.fields}+' !== \'undefined\' && d.'+${dfpl.fields}+' !== null?d.'+${dfpl.fields}+':\'\'}}'"></span>
        <i class="layui-icon layui-icon-form detail-edit" th:onclick="textareaBox(this,[[${dfpl.fields}]],[[${dfpl.fieldName}]],[[${gridColumnsZJ.readOnly}]])" style="float:right;z-index:999"></i>
    </script>
    <script type="text/html" th:if="${dfpl.fieldFrontType eq 't_dropdown'}" th:with="vtype=${#strings.substringAfter(#strings.substringAfter(dfpl.fieldSearchType,'_'),'_')}" th:id="'dropdown_'+${dfpl.fields}">
        <select th:data-field="${dfpl.fields}" th:with="map=${@baseinfosimple.getDropdownData(dfpl.fieldSearchType,dfpl.fieldFrontSave,dfpl.fieldFrontShow)}" lay-filter="select_table" fft="t_dropdown">
            <option></option>
            <div th:each="dict : ${map}" th:utext="'<option value=\''+${dict.vid}+'\' {{d.'+${dfpl.fields}+'==\''+${dict.vid}+'\'?\'selected\':\'\'}}>'+${dict.vname}+'</option>'" th:remove="tag"></div>
        </select>
    </script>
    <script type="text/html" th:if="${dfpl.fieldFrontType eq 't_dropdownedit'}" th:with="vtype=${#strings.substringAfter(#strings.substringAfter(dfpl.fieldSearchType,'_'),'_')}" th:id="'dropdownedit_'+${dfpl.fields}">
        <input type="text" th:value="'{{d.'+${dfpl.fields}+'}}'" class="layui-input" style="position:absolute;overflow:hidden;z-index:2;width: calc(100% - 33px);height: 30px;margin-top: 1px;margin-left: -7px;" th:onkeyup="inputSearchTable(this,[[${dfpl.fields}]])" autocomplete="off">
        <select th:lay-filter="${dfpl?.fields}+'_select'" autocomplete="off" class="layui-select" lay-search th:with="map=${@baseinfosimple.getDropdownData(dfpl.fieldSearchType,dfpl.fieldFrontSave,dfpl.fieldFrontShow)}">
            <option></option>
            <div th:each="dict : ${map}" th:utext="'<option value=\''+${dict.vid}+'\' {{d.'+${dfpl.fields}+'==\''+${dict.vid}+'\'?\'selected\':\'\'}}>'+${dict.vname}+'</option>'" th:remove="tag"></div>
        </select>
    </script>
    <script type="text/html" th:if="${dfpl.fieldFrontType eq 't_checkbox'}" th:id="'checkbox_'+${dfpl.fields}">
        <div th:utext="'<input type=\'checkbox\' value=\'true\' lay-skin=\'switch\' tName='+${dfpl.fields}+' tIndex=\'{{d.LAY_TABLE_INDEX}}\' lay-filter=\'switchTable\' lay-text=\'是|否\' data-field='+${dfpl.fields}+' {{d.'+${dfpl.fields}+'?\'checked\':\'\'}} '+(${dfpl.fieldFrontEdit or #bools.isTrue(checkProcessTask)}?'':'disabled')+'>'" th:remove="tag"></div>
    </script>
    <script type="text/html" th:if="${dfpl.fieldFrontType eq 't_file'}" th:id="'file_'+${dfpl.fields}">
        <input type="text" th:value="'{{d.'+${dfpl.fields}+'}}'" readonly style="border: none;background-color:rgba(0,0,0,0) !important;">
        <i class="layui-icon layui-icon-upload getDetailUpload" tGuid="{{d.guid}}" th:tName="${dfpl.fields}" style="float:right"></i>
    </script>
</div>
<!-- 明细特殊模板自生成 -->
<div th:each="dfpl:${gridColumnsJP.dictionaryForPageFieldList}" th:if="${dfpl.fieldFrontType ne 't_text'}" th:remove="tag">
    <script type="text/html" th:if="${dfpl.fieldFrontType eq 't_decimal' and #strings.containsIgnoreCase(dfpl.fieldFrontTemplet,'p_')}" th:id="'decimal_'+${dfpl.fields}">
        <span>{{d.[[${dfpl.fields}]] + '%'}}</span>
    </script>
    <script type="text/html" th:if="${(dfpl.fieldFrontType eq 't_date' or dfpl.fieldFrontType eq 't_datetime')}" th:id="'date_'+${dfpl.fields}">
        <input type="text" th:value="'{{d.'+${dfpl.fields}+'?d.'+${dfpl.fields}+':``}}'" th:fft="${dfpl.fieldFrontType}" class="layui-input layui-table-date2" style="position:absolute;overflow:hidden;z-index:2;left:0;margin:0;height:32px;padding-right:30px" autocomplete="off">
        <i class="dhicon dh-calendar icon_date_business" style="z-index:3;font-size:0"></i>
    </script>
    <script type="text/html" th:if="${dfpl.fieldFrontType eq 't_buttontext'}" th:id="'buttontext_'+${dfpl.fields}">
        <span th:text="'{{d.'+${dfpl.fields}+'}}'"></span>
        <i class="layui-icon layui-icon-more" th:onclick="getMore([[${dfpl.fields}]],{{d.LAY_TABLE_INDEX}},[[${dfpl.fieldName}]],[[${dfpl.fieldSearchType}]])" style="position:absolute;right:8px;z-index:3"></i>
    </script>
    <script type="text/html" th:if="${dfpl.fieldFrontType eq 't_buttontextedit'}" th:id="'buttontextedit_'+${dfpl.fields}">
        <input type="text" th:value="'{{d.'+${dfpl.fields}+'}}'" class="layui-input" style="position:absolute;overflow:hidden;z-index:2;left:0;margin:0;height:32px;padding-right:30px" th:onkeyup="inputOnTable(this,[[${dfpl.fields}]])" autocomplete="off">
        <i class="layui-icon layui-icon-more" th:onclick="getMore([[${dfpl.fields}]],{{d.LAY_TABLE_INDEX}},[[${dfpl.fieldName}]],[[${dfpl.fieldSearchType}]])" style="position:absolute;right:8px;z-index:3"></i>
    </script>
    <script type="text/html" th:if="${dfpl.fieldFrontType eq 't_textarea' or (dfpl.fieldFrontType eq 't_textarea' and gridColumnsJP.readOnly)}" th:id="'textarea_'+${dfpl.fields}">
        <span th:utext="'{{typeof d.'+${dfpl.fields}+' !== \'undefined\' && d.'+${dfpl.fields}+' !== null?d.'+${dfpl.fields}+':\'\'}}'"></span>
        <i class="layui-icon layui-icon-form detail-edit" th:onclick="textareaBox(this,[[${dfpl.fields}]],[[${dfpl.fieldName}]],[[${gridColumnsJP.readOnly}]])" style="float:right;z-index:999"></i>
    </script>
    <script type="text/html" th:if="${dfpl.fieldFrontType eq 't_dropdown'}" th:with="vtype=${#strings.substringAfter(#strings.substringAfter(dfpl.fieldSearchType,'_'),'_')}" th:id="'dropdown_'+${dfpl.fields}">
        <select th:data-field="${dfpl.fields}" th:with="map=${@baseinfosimple.getDropdownData(dfpl.fieldSearchType,dfpl.fieldFrontSave,dfpl.fieldFrontShow)}" lay-filter="select_table" fft="t_dropdown">
            <option></option>
            <div th:each="dict : ${map}" th:utext="'<option value=\''+${dict.vid}+'\' {{d.'+${dfpl.fields}+'==\''+${dict.vid}+'\'?\'selected\':\'\'}}>'+${dict.vname}+'</option>'" th:remove="tag"></div>
        </select>
    </script>
    <script type="text/html" th:if="${dfpl.fieldFrontType eq 't_dropdownedit'}" th:with="vtype=${#strings.substringAfter(#strings.substringAfter(dfpl.fieldSearchType,'_'),'_')}" th:id="'dropdownedit_'+${dfpl.fields}">
        <input type="text" th:value="'{{d.'+${dfpl.fields}+'}}'" class="layui-input" style="position:absolute;overflow:hidden;z-index:2;width: calc(100% - 33px);height: 30px;margin-top: 1px;margin-left: -7px;" th:onkeyup="inputSearchTable(this,[[${dfpl.fields}]])" autocomplete="off">
        <select th:lay-filter="${dfpl?.fields}+'_select'" autocomplete="off" class="layui-select" lay-search th:with="map=${@baseinfosimple.getDropdownData(dfpl.fieldSearchType,dfpl.fieldFrontSave,dfpl.fieldFrontShow)}">
            <option></option>
            <div th:each="dict : ${map}" th:utext="'<option value=\''+${dict.vid}+'\' {{d.'+${dfpl.fields}+'==\''+${dict.vid}+'\'?\'selected\':\'\'}}>'+${dict.vname}+'</option>'" th:remove="tag"></div>
        </select>
    </script>
    <script type="text/html" th:if="${dfpl.fieldFrontType eq 't_checkbox'}" th:id="'checkbox_'+${dfpl.fields}">
        <div th:utext="'<input type=\'checkbox\' value=\'true\' lay-skin=\'switch\' tName='+${dfpl.fields}+' tIndex=\'{{d.LAY_TABLE_INDEX}}\' lay-filter=\'switchTable\' lay-text=\'是|否\' data-field='+${dfpl.fields}+' {{d.'+${dfpl.fields}+'?\'checked\':\'\'}} '+(${dfpl.fieldFrontEdit or #bools.isTrue(checkProcessTask)}?'':'disabled')+'>'" th:remove="tag"></div>
    </script>
    <script type="text/html" th:if="${dfpl.fieldFrontType eq 't_file'}" th:id="'file_'+${dfpl.fields}">
        <input type="text" th:value="'{{d.'+${dfpl.fields}+'}}'" readonly style="border: none;background-color:rgba(0,0,0,0) !important;">
        <i class="layui-icon layui-icon-upload getDetailUpload2" tGuid="{{d.guid}}" th:tName="${dfpl.fields}" style="float:right"></i>
    </script>
</div>
<script th:inline="javascript">
	/*<![CDATA[*/
	var prefix = ctx + "business/productlisting",
    	prefix2 = ctx + "base/company";

	var fields = [[${fields}]];
    var fieldsList = [[${fieldsList}]];
	var fieldsHiddenList = [[${fieldsHiddenList}]];
	var moduleTable = [[${moduleTable}]];
	var pageType = [[${pageType}]];
	var enableEdit = [[${enableEdit}]];
	var productActive = [[${productActive}]];
	var ajaxResult = [[${ajaxResult}]];
	var gridColumnsZJ = [[${gridColumnsZJ}]];
	var gridColumnsJP = [[${gridColumnsJP}]];
	var productInfo = [[${productInfo}]];
    var gridColumns= [[${gridColumns}]];
    var ali1688AppKey = [[${ali1688AppKey}]],
        extraButton = [[${extraButton}]],
    ali1688EcpApiUrl =[[${ali1688EcpApiUrl}]],
    session=[[${session}]];//会话数据

	var all_fields= fieldsList;
    var code=""

    console.log("extraButton",extraButton)
    setTimeout(()=>{
        if(!extraButton.bcbtn){
            $('.fieldsimg').each(function () {
                $(this).nextAll().attr('type','')
            })
        }
    },1000)

	function sleep(time){
		var timeStamp = new Date().getTime();
		var endTime = timeStamp + time;
		while(true){
			if (new Date().getTime() > endTime){
				return;
			} 
		}
	}
	var $,layer,form,table;
    layui.use(['laydate','form','layer','jquery','util','element','upload','table'], function () {
        $ = layui.$,layer = layui.layer,form = layui.form,laydate = layui.laydate,util = layui.util,element=layui.element,upload = layui.upload,table = layui.table;
	    headcom2()
	    
	    var MAP_KEY_NAME = {};
        var files = '';
	    // 批量导入图片按钮绑定
        upload.render({
            elem: '#btn-batch-upload-img',
            url: window.updateurls,
            acceptMime: 'image/*',
            ext: 'jpg|png|gif|bmp|jpeg',
            multiple: true,
            before: function (obj) {
                files = obj.pushFile();
                this.data = {
                    'moduleFile': 'images'
                }
                
                var flag = true;
                for(var key in files){
                	var fileName = files[key].name;
                    var namePre = fileName.substring(0, fileName.indexOf('.'));
                    console.log('namePre---', namePre);
                    if('1|2|3|4|5|6|7|8|9|10|11|12|13|14|15'.indexOf(namePre) < 0) {
                    	flag = false;
                    }
                    MAP_KEY_NAME[key] = namePre;
                }
                if(flag == false) {
                	layer.msg('文件命名格式必须是指定数字格式，如：1.jpg');
                }
                return flag;
            },
            done: function (res, key) {
            	console.log('res--', res);
            	console.log('key--', key);
                //如果上传失败
                if (res.errno > 0) {
                    return layer.msg('上传失败');
                } else {
                    if (res.code == 500) {
                        return layer.msg(res.msg);
                    } else {
                    	
                    	console.log(MAP_KEY_NAME[key]);
                    	var namePre = MAP_KEY_NAME[key];
                        var filePath = res.data.filePath;
                        var id = '';
                    	if(namePre == 1) {
                    		id = 'vSpZt';
                    	} else if(namePre == 2) {
                    		id = 'vSpCct';
                    	} else if(namePre == 3) {
                    		id = 'vSpXjt1';
                    	} else if(namePre == 4) {
                    		id = 'vSpXjt2';
                    	} else if(namePre == 5) {
                    		id = 'vSpXjt3';
                    	} else if(namePre == 6) {
                    		id = 'vSpXjt4';
                    	} else if(namePre == 7) {
                    		id = 'vSpCjt1';
                    	} else if(namePre == 8) {
                    		id = 'vSpCjt2';
                    	} else if(namePre == 9) {
                    		id = 'vSpCjt3';
                    	} else if(namePre == 10) {
                    		id = 'vSpCjt4';
                    	} else if(namePre == 11) {
                    		id = 'img';
                    	} else if(namePre == 12) {
                    		id = 'img1';
                    	} else if(namePre == 13) {
                    		id = 'img2';
                    	}
                        layer.msg('上传成功');
                        delete files[key]
                        $('#' + id).val(filePath)
                        layui.$('#' + id + '_upimg').find('.upicon').addClass('layui-hide')
                        layui.$('#' + id + '_upimg').find('#uploadDemoView').removeClass('layui-hide').find('img').attr('src', filePath);
                    }
                }
            }, error: function (err) {
                //演示失败状态，并实现重传
                console.log(err)
            }
        });
        form.on('submit(btn-edit)', function(data){
            var is_return = false//是否中断保存
            fieldsList.map((v,i)=>{
                if(v.fieldFrontRequired){
                    if(!$('#'+v.fields).val()){
                         layer.msg(v.fieldName+'不能为空')
                         is_return=true
                    }
                }
            })
            if(is_return) return;
    	   var postStr = [];
		   postStr.push(data.field);
		   $.post("/business/productlisting/editpost",{productActiveItems:JSON.stringify([data.field])},function(res){
				 layer.msg(res.msg);
	       });
           return false;
       });
        form.on('submit(btn-export)', function(data){//导出
		   // postStr.push(data.field);
		   console.log("data",data.field.code)
            showloadings(true);
		   $.get("/business/productlisting/export2",{code:data.field.code},function(result){
               if (result.code == 0) {
                   window.location.href = ctx + "common/download?fileName=" + encodeURIComponent(result.msg) + "&delete=" + true;
                   parent.$('.page-loading').hide();//页面进行了跳转刷新，需要手动关闭页面的加载动画
               } else if (result.code == web_status.WARNING) {
                   $.modal.alertWarning(result.msg)
               } else {
                   $.modal.alertError(result.msg);
               }
               showloadings(false);
           });
           return false;
       });

        var tablestr=''
		$.each(gridColumnsZJ.gridBody,function(i,v){
			if(v.fieldFrontType=="t_decimal"){
				$('#'+v.field+' input').attr('type','number')
			}
		})
        $.each(gridColumnsJP.gridBody,function(i,v){
			if(v.fieldFrontType=="t_datetime"){
                console.log(v.templet)
                if(v.templet){
                    let ids=(v.templet).replace('#','')
                    console.log(ids)
                    tablestr+=``
                }
			}
		})

        var listData1=[]
        $.get("/business/productlisting/listzj?pcode="+code,function(res){
                listData1=res.data
	    });
        var listData2=[]
        $.get("/business/productlisting/listjp?pcode="+code,function(res){
                listData2=res.data
	    });

        setTimeout(function(){
            $.tablelist.init({
                elem: '#zjdhtable'
                ,data: listData1
                , page: false
                , even: true
                , limit: 10000
                , totalRow: gridColumnsZJ.totalRow
                , cols: [gridColumnsZJ.gridBody]
                , toolbar: '#zjtoolbar'
                , defaultToolbar: [{title: '列设置', layEvent: 'fieldSet', icon: 'layui-icon-set'}]
                , height: '400'
                , done: function (res, curr, count) {
                    listData1 = table.cache.zjdhtable;//每次重载都赋值更新表缓存
                },success:function(a,b,c){
                        console.log(a,b,c)
                }
            });
            $.tablelist.init({
                elem: '#jpdhtable'
                , data: listData2
                , page: false
                , even: true
                , limit: 10000
                , totalRow: gridColumnsJP.totalRow
                , cols: [gridColumnsJP.gridBody]
                , toolbar: '#jptoolbar'
                , defaultToolbar: [{title: '列设置', layEvent: 'fieldSet', icon: 'layui-icon-set'}]
                , height: '400'
                , done: function (res, curr, count) {
                    listData2 = table.cache.jpdhtable;//每次重载都赋值更新表缓存
                }
            });
            $('.layui-table-tool-self').hide()
            layuieach()
        },1000)



        $.each(gridColumnsZJ.gridNewLine, function (v, k) {//明细新增模板修改默认值
            if (k.substring(0, 1) == '#') gridColumnsZJ.gridNewLine[v] = $(k).val();
        })
        gridColumnsZJ.gridNewLine.deleted = 0;
        //头工具栏事件
        table.on('toolbar(zjtable)', function (obj) {
            switch (obj.event) {
                case 'addbtn':
                    listData1.push(gridColumnsZJ.gridNewLine);
				    reloadTable(listData1);
                    form.render();
                    layuieach()
                    break;
                case 'phbtn':
                    let cols=gridColumnsZJ.gridBody
                    var required=[]
                    $.each(cols, function (i, v) {
                        var title=v.title
                        if(title){
		    	    	    if(title.indexOf('<font class="f_red">*</font>') > -1){
                                required.push(v.field)
                            }
                        }
		    	    })
                    var isjx=true
                    $.each(table.cache.zjdhtable, function (i, v) {
                        v.guid=guid
		    	    	v.pcode=code
                        for(var n=0;n<required.length;n++){
                            var fild=required[n]
                            if(!v[fild]) isjx=false;
                        }
		    	    })
                    if(!isjx) return layer.msg('请填写必填项');

                    $.post(prefix + "/savezjpost", {'pcode':code,'productActiveComponentItems': JSON.stringify(table.cache.zjdhtable),}, function (res) {
                        if (res.code == 0){
                            var checkStatus = table.checkStatus('zjdhtable');
					        	checkStatus=checkStatus.data
                                if(checkStatus.length==0) return layer.msg('请勾选铺货数据');
                            $.modal.confirmCom('确定要铺货么？',function(result){
                                var isempty=false
                                var linkInMarkall = ""
					        	$.each(checkStatus,function(i,v){
                                    linkInMarkall+=(v.linkInMark+",")
                                    if(!v.linkInMark){
                                        isempty=true
                                    }
					        	})
                                if(isempty) return layer.msg('请填写选中的采购铺货标识');
							    linkInMarkall = linkInMarkall.substring(0,linkInMarkall.length-1)
					        	// orderID = orderID.substring(0,orderID.length-1)
                                console.log("code",$("#code").val(),$("#name").val())
					        	$.post(ali1688EcpApiUrl+'/api/1688/get1688ProductDetail',{'productNos':linkInMarkall,userId:session.userId,'pCode':$("#code").val(),'pName':$("#name").val()},function(result){
					        		layer.msg(res.msg);
					        	});
					        });
		    	    	}else{
		    	    		layer.msg(res.msg);
                        }
                    });
                    break;
                case 'fieldSet':
                    filedSet(moduleTable);
                    break;
            };
        });
        //编辑表格监听
        table.on('edit(zjtable)', function (obj) {
            var selector = obj.tr.selector + ' td[data-field="' + obj.field + '"] div';
            var oldtext = $(selector).text();// 单元格编辑之前的值
            var editField = obj.field,//编辑单元格fieId
                editRow = obj.data,//编辑单元格行数据
                dataindex = $(obj.tr.selector).attr('data-index'),//编辑单元格下标
                isReturn, editValue;
            // if (decimalObj[obj.field] > -1) {//判断是否数值字段
            //     editValue = checkEdit(obj, decimalObj);//判断输入是否为数值，否则还原数值
            //     setTableValue('zjdhtable', dataindex, editField, editValue);//通过dom给表格内控件渲染值
            //     listData1[dataindex][editField] = editValue;
            // }
        });
        //监听行事件
        table.on('tool(zjtable)', function (obj) {
            var data = obj.data, event = obj.event;
            switch (event) {
                case "del":
                    obj.del(); //删除对应行（tr）的DOM结构，并更新缓存
                    listData1 = table.cache.zjdhtable;
                    for (var i = 0; i < listData1.length; i++) if (!listData1[i] || listData1[i].length == 0) listData1.splice(i, 1);//删除一项
				    reloadTable(listData1);
                    break;
            }
        });
        form.on('submit(zjbtn_save)', function (data) {
            let cols=gridColumnsZJ.gridBody
            var required=[]
            $.each(cols, function (i, v) {
                var title=v.title
                if(title){
				    if(title.indexOf('<font class="f_red">*</font>') > -1){
                        required.push(v.field)
                    }
                }
			})
            var isjx=true
            $.each(table.cache.zjdhtable, function (i, v) {
                v.guid=guid
				v.pcode=code
                for(var n=0;n<required.length;n++){
                    var fild=required[n]
                    if(!v[fild]) {
                        isjx=false
                    };

                }
			})
            if(!isjx) return layer.msg('请填写必填项');

            $.operate.post(prefix + "/savezjpost", {'pcode':code,'productActiveComponentItems': JSON.stringify(table.cache.zjdhtable),}, function (res) {
                if (res.code == 0){
					layer.msg(res.msg);
				}
            });
        });



        $.each(gridColumnsJP.gridNewLine, function (v, k) {//明细新增模板修改默认值
            if (k.substring(0, 1) == '#') gridColumnsJP.gridNewLine[v] = $(k).val();
        })
        gridColumnsJP.gridNewLine.deleted = 0;
        //头工具栏事件
        table.on('toolbar(jptable)', function (obj) {
            switch (obj.event) {
                case 'addbtn':
                    listData2.push(gridColumnsJP.gridNewLine);
				    jpreloadTable(listData2);
                    form.render();
                    layuieach()
                    break;

                case 'fieldSet':
                    filedSet(moduleTable);
                    break;
            };
        });
        //编辑表格监听
        table.on('edit(jptable)', function (obj) {
            var selector = obj.tr.selector + ' td[data-field="' + obj.field + '"] div';
            var oldtext = $(selector).text();// 单元格编辑之前的值
            var editField = obj.field,//编辑单元格fieId
                editRow = obj.data,//编辑单元格行数据
                dataindex = $(obj.tr.selector).attr('data-index'),//编辑单元格下标
                isReturn, editValue;
        });
        //监听行事件
        table.on('tool(jptable)', function (obj) {
            var data = obj.data, event = obj.event;
            switch (event) {
                case "del":
                    obj.del(); //删除对应行（tr）的DOM结构，并更新缓存
                    listData2 = table.cache.jpdhtable;
                    for (var i = 0; i < listData2.length; i++) if (!listData2[i] || listData2[i].length == 0) listData2.splice(i, 1);//删除一项
				    jpreloadTable(listData2);
                    break;
            }
        });

        form.on('submit(btn_save)', function (data) {
            let cols=gridColumnsJP.gridBody
            var required=[]
            $.each(cols, function (i, v) {
                var title=v.title
                if(title){
				    if(title.indexOf('<font class="f_red">*</font>') > -1){
                        required.push(v.field)
                    }
                }
			})
            var isjx=true
            $.each(table.cache.jpdhtable, function (i, v) {
                v.guid=guid
				v.pcode=code
                for(var n=0;n<required.length;n++){
                    var fild=required[n]
                    if(!v[fild]){
                        isjx=false
                    }
                }
			})
            if(!isjx) return layer.msg('请填写必填项');

            $.operate.post(prefix + "/savejppost", {'pcode':code,'productActiveCompeteItems': JSON.stringify(table.cache.jpdhtable),}, function (res) {
                if (res.code == 0){
					layer.msg(res.msg);
				}
            });
        });

        assemblyhead()

        function layuieach(){
            $(".layui-table-date").each(function (i) {
	        	laydate.render({
	        		elem: this,
                    type: 'date',
            		trigger: 'click',
                    btns:['clear', 'now'],
            		done: function (value, date) {
            			var elemtr=$(this.elem).parents('tr').index();
            			var elem=$(this.elem).parents('td');
            			var datafield = elem.attr("data-field");
            			if (listData1[elemtr]) {
            				listData1[elemtr][datafield] = value;
            			}
            		}
	        	});
	        });
            $(".layui-table-date2").each(function (i) {
	        	laydate.render({
	        		elem: this,
                    type: 'date',
            		trigger: 'click',
                    btns:['clear', 'now'],
            		done: function (value, date) {
            			var elemtr = $(this.elem).parents('tr').index();
            			var elem = $(this.elem).parents('td');
            			var datafield = elem.attr("data-field");
            			if (listData2[elemtr]) {
            				listData2[elemtr][datafield] = value;
            			}
            		}
	        	});
	        });
            $(".getDetailUpload").each(function(){
                var that=this
                upload.render({
                    elem: that,
	                url: '/system/fileinfo/uploadmailimg',
	                accept: 'images',
	            	before: function(obj){
                        //预读本地文件示例，不支持ie8
                        obj.preview(function(index, file, result){
                          console.log(index, file, result)
                        });
                    },
	                done: function (res) {
                        //如果上传失败
                        if (res.errno > 0) {
                            return layer.msg('上传失败');
                        }else{
	            			layer.msg('上传成功');
                            layui.$(that).prevAll('input').value(res.data[0])
                            var elemtr = $(this.elem).parents('tr').index();
            			    var elem = $(this.elem).parents('td');
            			    var datafield = elem.attr("data-field");
                            if (res && listData1[elemtr]) {
            			    	listData1[elemtr][datafield] = res.data[0];
            			    }
	            		}
                    },error: function (err) {
                        //演示失败状态，并实现重传
	                	console.log(err)
                    }
                });
            })

            $(".getDetailUpload2").each(function(){
                var that=this
                upload.render({
                    elem: that,
	                url: '/system/fileinfo/uploadmailimg',
	                accept: 'images',
	            	before: function(obj){
                        //预读本地文件示例，不支持ie8
                        obj.preview(function(index, file, result){
                          console.log(index, file, result)
                        });
                    },
	                done: function (res) {
                        //如果上传失败
                        if (res.errno > 0) {
                            return layer.msg('上传失败');
                        }else{
	            			layer.msg('上传成功');
                            layui.$(that).prevAll('input').val(res.data[0])
                            var elemtr = $(this.elem).parents('tr').index();
            			    var elem = $(this.elem).parents('td');
            			    var datafield = elem.attr("data-field");
                            if (res && listData2[elemtr]) {
            			    	listData2[elemtr][datafield] = res.data[0];
            			    }
	            		}
                    },error: function (err) {
                        //演示失败状态，并实现重传
	                	console.log(err)
                    }
                });
            })
        }

		// beforeInit();//表单初始化之前的动作集合
		// layui.element.render();

    });


	function reloadTable(data){
        table.reload('zjdhtable', {data : data});
    }

	function jpreloadTable(data){
        table.reload('jpdhtable', {data : data});
    }


	function getQueryString(name) {
        var reg = new RegExp('(^|&)' + name + '=([^&]*)(&|$)', 'i');
        var r = window.location.search.substr(1).match(reg);
        if (r != null) {
         return unescape(r[2]);
        }
        return null;
    }
	var guid=getQueryString("guid");

	/*]]>*/
</script>

</body>
</html>